<template>
  <el-icon><User /></el-icon>当前用户：{{userName}}
  <br/>
  <br/>
  <el-form
      ref="userFormRef"
      :model="userForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
  >
    <el-form-item label="旧密码：" prop="oldPwd">
      <el-input type="password" v-model="userForm.oldPwd" placeholder="请输入旧密码" />
    </el-form-item>
    <el-form-item label="新密码：" prop="newPwd">
      <el-input type="password" v-model="userForm.newPwd" placeholder="请输入新密码" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup>
  import {ref,reactive,onMounted} from "vue";
  import request from "@/api/request";
  import {User} from '@element-plus/icons-vue'
  import {ElMessage} from "element-plus";
  import router from "@/router";

  const userName = ref('');
  const userFormRef = ref([]);
  const userForm = reactive({
    oldPwd:null,
    newPwd:null
  })
  const rules = reactive({
    oldPwd: [
      { required: true, message: '请输入旧密码', trigger: 'blur' }
    ],
    newPwd: [
      { required: true, message: '请输入新密码', trigger: 'blur' }
    ]
  })
  const submitForm = () => {
    userFormRef.value.validate((valid, fields)=>{
      if (valid) {
        request.put('/users/updpwd?newPwd='+userForm.newPwd+'&oldPwd='+userForm.oldPwd).then(resp=>{
          if (resp.code === 20000) {
            request.get('/user/logout').then(resp=>{
              localStorage.clear();
              sessionStorage.clear();
              router.replace('/login');
            })
            ElMessage.success(resp.data);
          } else {
            ElMessage.error(resp.data);
          }
        })
      }
    })
  }

  onMounted(()=>{
    request.get('/users/getuser').then(resp=>{
      if(resp){
        userName.value = resp.data.userName;
      }
    })
  })
</script>